package site.itaoke.config;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;

import java.util.Calendar;

/**
 * Created by sunfeihu on 2017/9/11.
 */
public class WeixinMsgController extends MsgControllerAdapter {

    static Log logger = Log.getLog(WeixinMsgController.class);

    @Override
    protected void processInTextMsg(InTextMsg inTextMsg) {
        String content = inTextMsg.getContent();
        if (content.startsWith("绑定")) {
            String openid = inTextMsg.getFromUserName();
            Record record = Db.findFirst(" select * from users where openid = ? ", new Object[]{
                    inTextMsg.getFromUserName()
            });
            if (null == record) {
                Db.update(" insert into users (nickname,openid,add_date) values (?,?,?)", content.substring(2), openid, Calendar.getInstance().getTime());
                OutTextMsg outMsg = new OutTextMsg(inTextMsg);
                outMsg.setContent("绑定成功");
                render(outMsg);
            }
        } else if (content.startsWith("openid")) {
            String openid = inTextMsg.getFromUserName();
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent(openid);
            render(outMsg);
        } else if (content.startsWith("订单")) {
            OutTextMsg outMsg = new OutTextMsg(inTextMsg);
            outMsg.setContent("<a href='http://wx.itaoke.site/moneys?openid=" + inTextMsg.getFromUserName() + "'>点我查看</a>");
            render(outMsg);
        }
    }


    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {

    }

    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        logger.debug("菜单事件：" + inMenuEvent.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
        outMsg.setContent("菜单事件内容是：" + inMenuEvent.getEventKey());
        render(outMsg);
    }

}
